from django import forms
from django.core.exceptions import ValidationError

from .models import ProductLotRel, ProductBaseInfo
from .models import User


class ProductLotRelForm(forms.ModelForm):
    class Meta:
        model = ProductLotRel
        fields = ['ProductType', 'LotNumber']
        widgets = {
            'ProductType': forms.TextInput(attrs={'maxlength': 256}),
            'LotNumber': forms.TextInput(attrs={'maxlength': 256}),
        }

    def clean_ProductType(self):
        data = self.cleaned_data['ProductType'].strip()
        if not data:
            raise forms.ValidationError("ProductType不能为空。")
        return data

    def clean_LotNumber(self):
        data = self.cleaned_data['LotNumber'].strip()
        if not data:
            raise forms.ValidationError("LotNumber不能为空。")
        return data

    def clean(self):
        cleaned_data = super().clean()
        product_type = cleaned_data.get('ProductType')
        lot_number = cleaned_data.get('LotNumber')

        # 检查数据库中是否存在相同的 ProductType 和 LotNumber 组合
        if ProductLotRel.objects.filter(ProductType=product_type, LotNumber=lot_number).exists():
            self.add_error('ProductType', '该产品类型和批号已经存在，请输入不同的值。')
            self.add_error('LotNumber', '该产品类型和批号已经存在，请输入不同的值。')

        return cleaned_data


class ProductLotRelUploadExcelForm(forms.Form):
    excel_file = forms.FileField(label='选择Excel文件')


class ProductBaseInfoForm(forms.ModelForm):
    class Meta:
        model = ProductBaseInfo
        fields = [
            'h_lot_number', 'h_product_type', 'report_number', 'report_date',
            'customer_name', 'order_number', 'production_lot_number',
            'specification_model', 'lot_quantity', 'direction_angle',
            'feeding_angle', 'frequency_range', 'frequency_measurement_gap',
            'customer_material_number', 'product_size', 'appearance_sample_quantity',
            'ma_accept', 'ma_reject', 'frequency_diff_limit', 'frequency_diff_control',
            'frequency_offset_degree'
        ]


class ProductAutoReportForm(forms.ModelForm):
    class Meta:
        model = ProductBaseInfo
        fields = [
            'h_lot_number', 'h_product_type', 'report_number', 'report_date',
            'customer_name', 'order_number', 'production_lot_number',
            'specification_model', 'lot_quantity', 'direction_angle',
            'feeding_angle', 'frequency_range', 'frequency_measurement_gap',
            'customer_material_number', 'product_size', 'appearance_sample_quantity',
            'ma_accept', 'ma_reject', 'frequency_diff_limit', 'frequency_diff_control',
            'frequency_offset_degree'
        ]

    size_data_address = forms.MultipleChoiceField(
        choices=[],
        widget=forms.CheckboxSelectMultiple,
        label="尺寸数据地址",
        initial=[]
    )
    angle_data_address = forms.MultipleChoiceField(
        choices=[],
        widget=forms.CheckboxSelectMultiple,
        label="直角度数据地址",
        initial=[]
    )
    frequency_data_address = forms.MultipleChoiceField(
        choices=[],
        widget=forms.CheckboxSelectMultiple,
        label="频率数据地址",
        initial=[]
    )
    df_data_address = forms.MultipleChoiceField(
        choices=[],
        widget=forms.CheckboxSelectMultiple,
        label="△F数据地址",
        initial=[]
    )

    def __init__(self, *args, **kwargs):
        size_files = kwargs.pop('size_files', [])
        angle_files = kwargs.pop('angle_files', [])
        frequency_files = kwargs.pop('frequency_files', [])
        df_files = kwargs.pop('df_files', [])
        super(ProductAutoReportForm, self).__init__(*args, **kwargs)
        self.fields['size_data_address'].choices = [(f, f) for f in size_files]
        self.fields['size_data_address'].initial = size_files
        self.fields['angle_data_address'].choices = [(f, f) for f in angle_files]
        self.fields['angle_data_address'].initial = angle_files
        self.fields['frequency_data_address'].choices = [(f, f) for f in frequency_files]
        self.fields['frequency_data_address'].initial = frequency_files
        self.fields['df_data_address'].choices = [(f, f) for f in df_files]
        self.fields['df_data_address'].initial = df_files

        # Set all fields as readonly
        for name, field in self.fields.items():
            if "_address" not in name:
                field.widget.attrs['readonly'] = True
                field.widget.attrs['disabled'] = True

    def clean_df_data_address(self):
        df_data_address = self.cleaned_data['df_data_address']
        if len(df_data_address) != 2:
            raise ValidationError("选择的△F数据地址必须是2个")
        return df_data_address

    def clean_frequency_data_address(self):
        frequency_data_address = self.cleaned_data['frequency_data_address']
        if len(frequency_data_address) < 1 or len(frequency_data_address) > 6:
            raise ValidationError("选择的频率数据地址必须大于1个小于等于6个")
        return frequency_data_address


class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ['username', 'password', 'role']
        widgets = {
            'password': forms.PasswordInput(),
        }


class ChangePasswordForm(forms.Form):
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}), label='新密码',
                               max_length=30)
    role = forms.ChoiceField(choices=User.ROLE_CHOICES, widget=forms.Select(attrs={'class': 'form-control'}),
                             label='角色')


class LoginForm(forms.Form):
    username = forms.CharField(max_length=20, widget=forms.TextInput(attrs={'class': 'form-control'}), label='用户名')
    password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control'}), label='密码')


class ProductUploadFileForm(forms.Form):
    file = forms.FileField(label='选择Excel文件')
